<?php

/**
 * Description of LiveRankings
 *
 * @author De Cramer Oliver
 */

namespace ManiaLivePlugins\MLEPP\Widgets\Widgets\Controlers\Defaults\endRace_PlayTime;

use ManiaLive\PluginHandler\PluginHandler;

class Standard extends \ManiaLivePlugins\MLEPP\Widgets\Structures\TypeController {

	private $mlepp;

	public function onInit() {
		parent::onInit();
		$this->setVersion(0.1);
		$this->setWhenToShow(2);
		$this->mlepp = \ManiaLivePlugins\MLEPP\Core\Mlepp::getInstance();
		$this->setIsUnique(true);
	}

	public function onEndMap($rankings, $challenge, $wasWarmUp, $matchContinuesOnNextChallenge, $restartChallenge) {
		$this->data = array();
		$this->resetWidgetData();

		$sql = " SELECT *
					FROM players
					ORDER BY player_timeplayed DESC
					LIMIT 0, " . $this->settings->nbFirst;
		$result = $this->mlepp->db->query($sql);

		if ($result->recordCount() > 0) {
			$i = 1;
			while ($data = $result->fetchStdObject()) {
				$player = new \ManiaLivePlugins\MLEPP\Widgets\Structures\smallPlayer();
				$player->login = $data->player_login;
				$player->nickName = $data->player_nickname;
				$player->rank = $i;
				$player->score = $this->formatTime($data->player_timeplayed);
				$this->data[$i] = $player;
				$i++;
			}
		}
		$this->updateWidgetData($this->data);
		parent::onEndMap($rankings, $challenge, $wasWarmUp, $matchContinuesOnNextChallenge, $restartChallenge);
	}

	private function formatTime($seconds) {
		$minutes = (int) ($seconds / 60);
		if ($minutes > 60) {
			$rtn = "";
			$hours = (int) ($seconds / (3600));
			$days = (int) ($seconds / 24 / 3600);
			$hours = $hours - ($days * 24);
			if ($days > 1)
				$rtn = $days . "day ";
			if ($hours >= 1)
				$rtn .= $hours . "h";
			return $rtn;
		} else {
			return $minutes . "min";
		}
	}

	function destroy() {
		parent::destroy();
		gc_collect_cycles();
	}

}

?>
